package com.sky.task;

import com.sky.dto.OrdersStatusAllDTO;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import static com.sky.entity.Orders.*;

/**
 * 定时任务
 * 每分钟检查一次是否存在支付超时订单（下单后超过15分钟仍未支付则判定为支付超时订单）
 * 如果存在则修改订单状态为“已取消”
 * @author yangkexuan
 * @className MyTask
 * @date 2023/6/15 19:35
 * @description
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;
    /**
     * 定时任务 每1min触发一次
     * 检测订单超时
     */
    @Scheduled(cron = "0 * * * * ?")
    public void detectOrderTimeout(){
        //查询所有状态为 1： 未支付 的订单时间
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //获取超过15分钟未支付的订单的id
        List<Long> id = orderMapper.selectPayTime(PENDING_PAYMENT,time);
        //将状态更新为6已取消
        for (Long aLong : id) {
            OrdersStatusAllDTO orders = new OrdersStatusAllDTO();
            orders.setId(aLong).setStatus(CANCELLED).setCancelReason("订单支付超时，自动取消").setCancelTime(LocalDateTime.now());
            orderService.updateCancelOrder(orders);
        }
        if(!id.isEmpty()){
            log.info("处理支付超时订单：{}",new Date());
        }

    }

    /**
     * 定时任务，每天执行一次
     * 天凌晨1点检查一次是否存在“派送中”的订单，如果存在则修改订单状态为“已完成”
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void checkDeliveryStatus(){
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);
        //4 派送中
        List<Long> id = orderMapper.selectPayTime(DELIVERY_IN_PROGRESS,time);
        for (Long aLong : id) {
            OrdersStatusAllDTO orders = new OrdersStatusAllDTO();
            orders.setId(aLong).setStatus(COMPLETED);
            orderService.updateCancelOrder(orders);
        }
        log.info("处理派送中”的订单：{}",new Date());
    }
}
